<?php

namespace app\service;

use support\Redis;
use Workerman\Mqtt\Client;

class MqttServer
{
    protected $mqtt;
    public function __construct()
    {
        $this->mqtt=new Client('mqtt://127.0.0.1:1883');
    }

    /**
     * 发布主题
     * @param $topic
     * @param $content
     * @return void
     */
    public function publish($topic,$content)
    {

        $data_array=json_decode(Redis::get('topic'),true);
        if (empty($data_array)){
            Redis::set('topic',json_encode([$topic=>0]));
        }else{
            //判断是否在数组中
            if (!array_key_exists($topic,$data_array)){
                $data_array[$topic] = 0;
                Redis::del('topic');
                Redis::set('topic',json_encode($data_array));
            }
        }
        $mqtt_server=$this->mqtt;
        $mqtt_server->onConnect = function()use($topic,$content,$mqtt_server) {
            $mqtt_server->publish($topic, $content);
        };
        $mqtt_server->connect();

    }
}
